package com.cn.zpark.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @PackageName: com.cn.zpark.filter
 * @ClassName: FilterDemo03
 * @Description:
 * @author: RZS
 * @date: 2022/4/15  8:18
 */
public class FilterDemo03 implements Filter {

    private String initName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("FilterDemo03初始化成功");

        // 获取filter初始化参数
        String name = filterConfig.getInitParameter("name");
        this.initName = name;
        System.out.println(name);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 设置请求缓冲区
        req.setCharacterEncoding("utf-8");
        // 设置响应内容及格式
        resp.setContentType("text/html;charset=utf-8");

        System.out.println("FilterDemo03过滤器");

        // 如果请求参数中有name为张三的，则拦截，否则放行
        String uname = req.getParameter("uname");
        if(initName.equals(uname)){
            // 含有name为张三的人，拦截

        }else{
            // 放行，访问后面的资源
            chain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {
        System.out.println("FilterDemo03被销毁");
    }
}
